package com.wydpp.gb28181.processor.response.impl;

import com.wydpp.domain.Device;
import com.wydpp.gb28181.bean.SipPlatform;
import com.wydpp.gb28181.commander.SIPCommander;
import com.wydpp.gb28181.processor.SIPProcessorObserver;
import com.wydpp.gb28181.processor.response.SIPResponseProcessorAbstract;
import com.wydpp.repository.DeviceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.ResponseEvent;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.WWWAuthenticateHeader;
import javax.sip.message.Response;

/**
 * @description:Register响应处理器
 * @author: wydpp
 * @date: 2021年12月2日
 */
@Slf4j
@Component
public class RegisterResponseProcessor extends SIPResponseProcessorAbstract {

    private String method = "REGISTER";

    @Autowired
    private SIPProcessorObserver sipProcessorObserver;

    @Autowired
    private SIPCommander sipCommander;

    @Autowired
    private SipPlatform sipPlatform;

    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        sipProcessorObserver.addResponseProcessor(method, this);
    }

    /**
     * 处理Register响应
     *
     * @param evt 事件
     */
    @Override
    public void process(ResponseEvent evt) {
        Response response = evt.getResponse();
        CallIdHeader callIdHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME);
        ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
        String string = toHeader.getAddress().getURI().toString();
        String deviceId = extractDeviceIdFromUri(string);
        Device device = deviceRepository.findDeviceByDeviceId(deviceId);
        String callId = callIdHeader.getCallId();
        int statusCode = response.getStatusCode();
        String platformInfo = sipPlatform.getServerIP() + ":" + sipPlatform.getServerPort();
        if (statusCode == 401) {
            // 携带验证信息
            WWWAuthenticateHeader authorizationHeader = (WWWAuthenticateHeader) response.getHeader(WWWAuthenticateHeader.NAME);
            if (!device.getNeedRegister()) {
                log.info("向平台:{} 发送带认证信息的注册消息!", platformInfo);
                sipCommander.register(sipPlatform, device, callId, authorizationHeader, null);
            } else {
                log.info("向平台:{} 发送带认证信息的注销消息!", platformInfo);
                sipCommander.unRegister(sipPlatform, device, callId, authorizationHeader, null);
            }

        } else if (statusCode == 200) {
            if (!device.getNeedRegister()) {
                log.info("设备向平台:{} 注册成功!", platformInfo);
            } else {
                log.info("设备向平台:{} 注销成功!", platformInfo);
            }
        } else {
            log.info("设备向平台:{} 注册失败!", platformInfo);
        }
    }


    public String extractDeviceIdFromUri(String sipUri) {
        // SIP URI 格式：sip:user@domain:port
        // 提取出设备 ID
        String[] uriParts = sipUri.split("@");
        if (uriParts.length > 1) {
            String userPart = uriParts[0].replace("sip:", "");  // 获取 user 部分
            return userPart;
        }
        return null;  // 如果无法提取设备 ID，则返回 null
    }

}
